<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
    <link th:href="@{css/webuploader.css}" rel="stylesheet">
    <style type="text/css">
        /**{*/
        /*    list-style: none;*/
        /*}*/
        /*.itemDel,.itemClear,.itemStop, .itemUpload{*/
        /*    width: 70px;*/
        /*    !*background: skyblue;*!*/
        /*    float: right;*/
        /*    margin-right: 10px;*/
        /*    margin-top: 10px;*/
        /*    !*margin-left: 15px;*!*/
        /*    !*float: left;*!*/
        /*    color: blue;*/
        /*    cursor: pointer;*/
        /*    font-size: 14px;*/
        /*    font-weight: bold;*/
        /*    letter-spacing: 2px;*/
        /*}*/
        /*.itemClear{*/
        /*    margin-right: 90px;*/
        /*}*/
        /*#theList{*/
        /*    width: 80%;*/
        /*    min-height: 100px;*/
        /*    margin-left: 10%;*/
        /*    border-radius: 5px;*/
        /*    border: 1px solid red;*/
        /*}*/
        /*#theList .itemStop,#theList .itemClear{*/
        /*    display: none;*/
        /*}*/
        /*.video_info{*/
        /*    color: #000;*/
        /*    font-size: 14px;*/
        /*    font-weight: bold;*/
        /*    letter-spacing: 1px;*/
        /*}*/
        /*.default_box{*/
        /*    !*position: absolute;*!*/
        /*    float: left;*/
        /*    margin-left: 1%;*/
        /*    margin-top: 2%;*/
        /*    display: inline-block;*/
        /*    width: 30%;*/
        /*    height: 15px;*/
        /*    !*background-image: -webkit-linear-gradient(top,#535559,#ddd,#535559);*!*/
        /*    !*background: #ddd;*!*/
        /*    border-radius: 15px;*/

        /*    background: -moz-linear-gradient(top,#535559,#ddd,#535559);*/
        /*    background: -webkit-gradient(top,#535559,#ddd,#535559);*/
        /*    background: -webkit-linear-gradient(top,#535559,#ddd,#535559);*/
        /*    background: -o-linear-gradient(top,#535559,#ddd,#535559);*/
        /*    background: -ms-linear-gradient(top,#535559,#ddd,#535559);*/
        /*    background: linear-gradient(top,#535559,#ddd,#535559);*/
        /*}*/
        /*.default_box>.show_box{*/
        /*    position: relative;*/
        /*    !*z-index: 5;*!*/
        /*    display: inline-block;*/
        /*    height: 100%;*/
        /*    !*background-image: -webkit-linear-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*!*/
        /*    !*background: #C5F2FF;*!*/
        /*    border-radius: 15px;*/

        /*    background: -moz-linear-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*/
        /*    background: -webkit-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*/
        /*    background: -webkit-linear-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*/
        /*    background: -o-linear-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*/
        /*    background: -ms-linear-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*/
        /*    background: linear-gradient(top,#93E7FE,#C5F2FF,#8EE7FF,#005870,#00B4E6,#00B4E6);*/
        /*}*/
        /*.file_name{*/
        /*    !*display: block;*!*/
        /*    float: left;*/
        /*    margin-top: 10px;*/
        /*    width: 85%;*/
        /*    !*background: red;*!*/

        /*    overflow:hidden;*/
        /*    word-break:keep-all;*/
        /*    white-space:nowrap;*/
        /*    text-overflow:ellipsis;*/
        /*}*/
        /*.percentage{*/
        /*    width: 15%;*/
        /*    !*background: blue;*!*/
        /*    margin-top: 2%;*/
        /*    float: left;*/
        /*    margin-left: 1%;*/
        /*}*/
        *{
            list-style: none;
            margin: 0;
            padding: 0;
        }
        #theList{
            position: relative;
            width: 80%;
            min-height: 600px;
            margin-left: 10%;
            /* border-radius: 5px; */
            border: 1px solid #ddd;
        }
        .video_info,.video_info_title{
            position: relative;
            display: inline-block;
            float: left;
            width: 100%;
            height: 80px;
            border-bottom: 1px solid #ddd;
            /* background-color: green; */
            color: #000;
            font-size: 14px;
            font-weight: bold;
            letter-spacing: 1px;
            line-height: 80px;
            /* background-color: red; */
        }
        .video_info_title{
            background-color: #eee;
        }
        .percentage{
            position: absolute;
            top: 0;
            left: 0;
            width: 0%;
            height: 100%;
            background-color: #aaffff;
            z-index: -1;
        }
        #theList .itemStop,#theList .itemClear{
            display: none;
        }
        .itemDel,.itemClear,.itemStop,.itemUpload,.US,.DC{
            display: inline-block;
            width: 100px;
            font-weight: bold;
            letter-spacing: 2px;
            text-align: center;
        }
        .itemDel,.itemClear,.itemStop,.itemUpload{
            color: blue;
            cursor: pointer;
            font-size: 14px;
        }
        .itemUpload, .itemStop, .US{
            position: absolute;
            right: 120px;
        }
        .itemDel, .itemClear, .DC{
            position: absolute;
            right: 10px;
        }
        .text_info{
            position: absolute;
            right: 240px;
        }
        .file_name{
            float: left;
            margin-left: 8px;
            width: 85%;

            overflow:hidden;
            word-break:keep-all;
            white-space:nowrap;
            text-overflow:ellipsis;
        }
        .video_all{
            width: 100px;
            height: 40px;
            text-decoration: none;
            display: inline-block;
            border-radius: 3px;
            user-select: none;
            background: #4AB2FE;
            /*width: 60px;*/
            /*height: 30px;*/

            color: #fff;
            font-size: 15px;
            font-weight: bold;
            text-align: center;
            line-height: 40px;
            letter-spacing: 3px;
        }
    </style>
    <script th:src="@{js/jquery-1.10.2.min.js}" type="text/javascript" charset="utf-8"></script>
    <script th:src="@{js/md5.js}" type="text/javascript" charset="utf-8"></script>
    <script th:src="@{js/webuploader.js}" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    <div id="uploader">
        <div id="picker">选择文件</div>
        <ul id="theList">
            <li class="video_info_title">
                <span class="file_name">文件</span>
                <span class="US">上传/暂停</span>
                <span class="DC">删除/清除</span>
            </li>
        </ul>
    </div>
    <a class="video_all" th:href="${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort()  + #request.getContextPath() + '/queryAll'}">全部视频</a>


    <script type="text/javascript">
        var userInfo = {userId:"admin", md5:""};   //用户会话信息，userId是用来区分用户的，并且可以区分
        var chunkSize = 5000 * 1024;        //分块大小
        var uniqueFileName = null;          //文件唯一标识符
        var md5Mark = null;

        var last_file_id = null;
        var is_video = false;

        var vid = null;
        var vpath = null;
        var suffix = null;

        //获取当前网址
        var curWwwPath=window.document.location.href;
        //获取主机地址之后的目录
        var pathName=window.document.location.pathname;
        var pos=curWwwPath.lastIndexOf(pathName);
        //获取主机地址
        var localhostPaht=curWwwPath.substring(0,pos);

        var backEndUrl = localhostPaht+"/fileUpload";
        var clearChunksUrl = localhostPaht+"/clearChunks";
        console.log("backEndUrl："+backEndUrl+",clearChunksUrl："+clearChunksUrl);

        WebUploader.Uploader.register({
            "before-send-file": "beforeSendFile"
            , "before-send": "beforeSend"
            , "after-send-file": "afterSendFile"
        }, {
            beforeSendFile: function(file){
                //秒传验证
                // console.log('信息：'+userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size)
                var task = new $.Deferred();
                // var start = new Date().getTime();
                (new WebUploader.Uploader()).md5File(file, 0, 10*1024*1024).progress(function(percentage){
                    console.log("percentage——"+percentage);
                }).then(function(val){
                    // console.log(val)
                    // console.log("总耗时: "+((new Date().getTime()) - start)/1000);

                    md5Mark = val;
                    userInfo.md5 = val;

                    $.ajax({
                        type: "POST"
                        , url: backEndUrl
                        , data: {
                            status: "md5Check"
                            , md5: val
                            , vid: vid
                            , vpath: vpath
                            , suffix: suffix
                        }
                        , cache: false
                        , timeout: 1000 //todo 超时的话，只能认为该文件不曾上传过
                        , dataType: "json"
                    }).then(function(data, textStatus, jqXHR){

                        // console.log("data:"+data);

                        if(data.ifExist){   //若存在，这返回失败给WebUploader，表明该文件不需要上传
                            task.reject();

                            uploader.skipFile(file);
                            file.path = data.path;
                            UploadComlate(file);
                        }else{
                            task.resolve();
                            //拿到上传文件的唯一名称，用于断点续传
                            uniqueFileName = md5(''+userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size);
                        }
                    }, function(jqXHR, textStatus, errorThrown){    //任何形式的验证失败，都触发重新上传
                        task.resolve();
                        //拿到上传文件的唯一名称，用于断点续传
                        uniqueFileName = md5(''+userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size);
                    });
                });
                return $.when(task);
            },
            beforeSend: function(block){
                // console.log("断点续传")
                //分片验证是否已传过，用于断点续传
                var task = new $.Deferred();
                $.ajax({
                    type: "POST"
                    , url: backEndUrl
                    , data: {
                        status: "chunkCheck"
                        , name: uniqueFileName
                        , chunkIndex: block.chunk
                        , size: block.end - block.start
                    }
                    , cache: false
                    , timeout: 1000 //todo 超时的话，只能认为该分片未上传过
                    , dataType: "json"
                }).then(function(data, textStatus, jqXHR){
                    if(data.ifExist){   //若存在，返回失败给WebUploader，表明该分块不需要上传
                        // console.log(true)
                        $(".video_info>.text_info").text("正在检索...");
                        task.reject()
                    }else{
                        // console.log(false)
                        var text = $(".video_info>.text_info").text();
                        // console.log(text);
                        if(text == "正在检索..."){
                            $(".video_info>.text_info").text("");
                        }
                        $(".default_box").css({"display":"block"});
                        task.resolve();
                    }
                }, function(jqXHR, textStatus, errorThrown){    //任何形式的验证失败，都触发重新上传
                    task.resolve();
                });

                return $.when(task);
            }
            , afterSendFile: function(file){
                // console.log("分片合并")
                var chunksTotal = 0;
                if((chunksTotal = Math.ceil(file.size/chunkSize)) > 1){
                    //合并请求
                    var task = new $.Deferred();
                    $.ajax({
                        type: "POST"
                        , url: backEndUrl
                        , data: {
                            status: "chunksMerge"
                            , name: uniqueFileName
                            , chunks: chunksTotal
                            , ext: file.ext
                            , md5: md5Mark
                        }
                        , cache: false
                        , dataType: "json"
                    }).then(function(data, textStatus, jqXHR){

                        //todo 检查响应是否正常

                        task.resolve();
                        file.path = data.path;
                        UploadComlate(file);
                        vid = data.vid;
                        vpath = data.vpath;

                    }, function(jqXHR, textStatus, errorThrown){
                        task.reject();
                    });

                    return $.when(task);
                }else{
                    UploadComlate(file);
                    vid = data.vid;
                    vpath = data.vpath;
                }
            }
        });

        var uploader = WebUploader.create({
            swf: "Uploader.swf"
            , server: backEndUrl
            , pick: "#picker"
            , resize: false
            , dnd: "#theList"
            , paste: document.body
            , disableGlobalDnd: true
            , thumb: {
                width: 100
                , height: 100
                , quality: 70
                , allowMagnify: true
                , crop: true
            }
            , compress: false
            , prepareNextFile: true
            , chunked: true
            , chunkSize: chunkSize
            , threads: true
            , formData: function(){return $.extend(true, {}, userInfo);}
            , fileNumLimit: 2
            , fileSingleSizeLimit: 2000 * 1024 * 1024
            , duplicate: true
            , accept:{
                title:'视频上传',
                extensions:'mp4,avi,flv'
            }
        });

        uploader.on("fileQueued", function(file){

            var suffix = file.name.split(".")[1];
            if(last_file_id != null) {
                uploader.removeFile(last_file_id);
                $("#" + last_file_id).remove();
            }
            $("#theList").append('<li id="'+file.id+'" class="video_info">' +
                '<img /><span class="file_name">'+file.name+
                '</span><span class="itemDel">删除</span><span class="itemClear">清除</span><span class="itemUpload">上传</span><span class="itemStop">暂停</span>' +
                '<div class="percentage"></div><span class="text_info">ts</span>' +
                '</li>');

            last_file_id = file.id;

        });

        $("#theList").on("click", ".itemUpload", function(){
            var id = $(this).parent().attr("id");
            console.log("this = "+this);
            console.log("id = "+$(this).parent().attr("id"));
            uploader.upload();
            // console.log("上传");
            //"上传"-->"暂停"

            $(this).hide();
            $(".itemStop").show();
        });

        $("#theList").on("click", ".itemStop", function(){
            uploader.stop(true);
            // console.log("暂停");
            //"暂停"-->"上传"
            $(this).hide();
            $(".itemUpload").show();
        });

        //todo 如果要删除的文件正在上传（包括暂停），则需要发送给后端一个请求用来清除服务器端的缓存文件
        $("#theList").on("click", ".itemDel", function(){
            // console.log("删除："+$(this).parent().attr("id"));
            uploader.stop(true);    // 暂定上传操作
            setTimeout(function (){
                $.ajax({    // 发送请求到后台，然后删除分片和temp文件
                    type: 'POST',
                    url: clearChunksUrl,
                    data: {
                        name: uniqueFileName
                        , chunks: -1
                        , ext: suffix
                        , md5: md5Mark
                    }
                })
                uploader.removeFile($(this).parent().attr("id"));	//从上传文件列表中删除
            },100);


            $(this).parent().remove();	//从上传列表dom中删除
        });

        $("#theList").on("click",".itemClear",function (){
            uploader.removeFile($(this).parent().attr("id"));	//从上传文件列表中删除
            $(this).parent().remove();	//从上传列表dom中删除
        })

        uploader.on("uploadProgress", function(file, percentage){
            var text = $("#" + file.id + " .percentage").text();
            if(text != '正在检索...'){
                const now_percentage = Math.round(percentage*10000)/100;
                $(".percentage").css({"width":now_percentage + "%"});
                // $("#" + file.id + " .percentage").text(now_percentage + "%");
            }
            if(percentage >= 1){
                $(".itemDel").hide();
                $(".itemStop").hide();
                $(".itemUpload").hide();
                // $(".default_box").hide();
                $("#" + file.id + " .text_info").text("正在处理");
                is_video = true;
            }
        });

        function UploadComlate(file){
            // console.log(file);
            // console.log("file_id："+$("#" + file.id).attr("id"));
            $("#" + file.id + " .text_info").text("上传完毕");
            $(".itemClear").show();

            uploader.removeFile($("#" + file.id).attr("id"));
        }

    </script>
</body>
</html>